import 'package:flutter/material.dart';
import 'dart:io';
import 'package:image_picker/image_picker.dart';
import 'package:shared_preferences/shared_preferences.dart';

class MyIndexedStack extends StatefulWidget{
  const MyIndexedStack({super.key});

  @override
  State<StatefulWidget> createState() {
    return _MyIndexedStack();
  }
}
class _MyIndexedStack extends State<MyIndexedStack>{
  int _pageIndex = 0;
  // ignore: unnecessary_new
  final ImagePicker picker = new ImagePicker();
  String str11 = "https://img2.baidu.com/it/u=537058032,362780022&fm=253&fmt=auto&app=138&f=JPEG?w=612&h=459";
  // ignore: prefer_typing_uninitialized_variables
  var str1 ;
  String str22 = "http://mms0.baidu.com/it/u=1865154727,2256024073&fm=253&app=138&f=JPEG?w=260&h=260";
  // ignore: prefer_typing_uninitialized_variables
  var str2  ;
  @override
  Widget build(BuildContext context) {
        return MaterialApp(
          debugShowCheckedModeBanner: false,
          home: Scaffold(
            body: IndexedStack(
              index: _pageIndex,
              children: [
                str1==null?Image.network(str11):Image.file(File(str1),fit: BoxFit.fill,),
                str2==null?Image.network('https://img1.baidu.com/it/u=2702146462,2523734973&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=666'):Image.file(File(str2),fit: BoxFit.fill,),
              ],
            ),
            floatingActionButton: FloatingActionButton(
              onPressed: (){
                _pageIndex = _pageIndex==0?1:0;
                if(_pageIndex==1){
                  _getCameraImage();
                }else{
                  _getGalleryImage();
                }
                setState(() {

                });
              },
              child: const Icon(Icons.add),
            ),
          )

        );
  }
  //进入系统相机拍照，str1就是拍的图片的路径
  Future _getCameraImage() async{
     final cameraImages = await picker.pickImage(source: ImageSource.camera);
     if(mounted){
       setState(() {
         if(cameraImages!=null){
           str1 = cameraImages.path;
           // ignore: avoid_print
           print('camera路径为:${cameraImages.path}');
         }
       });
     }
  }
  //进入系统相册，str2就是选择的图片的地址
  Future _getGalleryImage() async{
    final galleryImages = await picker.pickImage(source: ImageSource.gallery);
    if(mounted){
      setState(() {
        if(galleryImages!=null){
          str2 = galleryImages.path;
          // ignore: avoid_print
          print('gallery路径为:${galleryImages.path}');
        }
      });
    }
  }
}



class SettingsPage extends StatefulWidget {
  const SettingsPage({Key? key}) : super(key: key);

  @override
  // ignore: library_private_types_in_public_api
  _SettingsPageState createState() => _SettingsPageState();
}

class _SettingsPageState extends State<SettingsPage> {
  // ignore: unused_field
  late File _selectedImage;
  late SharedPreferences _prefs;

  @override
  void initState() {
    super.initState();
    // 调用 _loadPrefs 方法来初始化 _selectedImage 变量
    _loadPrefs();
  }

  Future<File> _loadPrefs() async {
    _prefs = await SharedPreferences.getInstance();
    final imagePath = _prefs.getString('imagePath');
    if (imagePath != null) {
      return File(imagePath);
    } else {
      return File('assets/touxiang.jpg');
    }
  }

  Future<void> _saveImagePath(String imagePath) async {
    await _prefs.setString('imagePath', imagePath);
  }

  // ignore: unused_element
  Future<void> _pickImage(ImageSource source) async {
    final picker = ImagePicker();
    final pickedImage = await picker.pickImage(source: source);
    if (pickedImage != null) {
      setState(() {
        _selectedImage = File(pickedImage.path);
      });
      _saveImagePath(pickedImage.path);
    }
  }


  void _updateSelectedImage(File image) {
    setState(() {
      _selectedImage = image;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView(
        children: [
          Container(
            padding: const EdgeInsets.all(16),
            color: Colors.grey[200],
            child: Row(
              children: [
                // 使用 FutureBuilder 来等待异步操作完成，避免 LateInitializationError 错误
                FutureBuilder(
                  future: _loadPrefs(),
                  builder: (BuildContext context, AsyncSnapshot<File> snapshot) {
                    if (snapshot.connectionState == ConnectionState.done) {
                      return InkWell(
                        onTap: () {
                          showDialog(
                            context: context,
                            builder: (BuildContext context) {
                              return AlertDialog(
                                title: const Text('选择头像'),
                                actions: [
                                  TextButton(
                                    child: const Text('从相册选择'),
                                    onPressed: () async {
                                      Navigator.of(context).pop();
                                      final pickedImage = await ImagePicker().pickImage(source: ImageSource.gallery);
                                      if (pickedImage != null) {
                                        _updateSelectedImage(File(pickedImage.path));
                                        _saveImagePath(pickedImage.path);
                                      }
                                    },
                                  ),
                                  TextButton(
                                    child: const Text('拍照'),
                                    onPressed: () async {
                                      Navigator.of(context).pop();
                                      final pickedImage = await ImagePicker().pickImage(source: ImageSource.camera);
                                      if (pickedImage != null) {
                                        _updateSelectedImage(File(pickedImage.path));
                                        _saveImagePath(pickedImage.path);
                                      }
                                    },
                                  ),
                                ],
                              );
                            },
                          );
                        },
                        // 使用条件运算符来检查 _selectedImage 是否为 null，并使用默认头像路径
                        child: CircleAvatar(
                          radius: 40,
                          backgroundImage: snapshot.data != null ? FileImage(snapshot.data!) as ImageProvider<Object>?: const AssetImage('assets/touxiang.jpg'),
                        ),
                      );
                    } else {
                      return const CircularProgressIndicator();
                    }
                  },
                ),
                const SizedBox(width: 16),
                const Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '江上清风山间明月',
                      style: TextStyle(fontSize: 18),
                    ),
                    Text(
                      '用户ID: 123456',
                      style: TextStyle(fontSize: 14, color: Colors.grey),
                    ),
                  ],
                ),
              ],
            ),
          ),
          const Divider(indent: 60,),
          const SettingItem(icon: Icons.person, title: '个人信息'),
          const Divider(indent: 60,),
          const SettingItem(icon: Icons.lock, title: '账号与安全'),
          const Divider(indent: 60,),
          const SettingItem(icon: Icons.notifications, title: '消息通知'),
          const Divider(indent: 60,),
          const SettingItem(icon: Icons.language, title: '语言'),
          // 添加更多的设置项...
        ],
      ),
    );
  }
}

class SettingItem extends StatelessWidget {
  final IconData icon;
  final String title;

  const SettingItem({super.key, required this.icon, required this.title});

  @override
  Widget build(BuildContext context) {
    return ListTile(
      leading: Icon(icon),
      title: Text(title),
      trailing: const Icon(Icons.arrow_forward_ios),
      onTap: () => {},
    );
  }
}




// class MyHomePage extends StatefulWidget {
//   const MyHomePage({super.key});
  
//   @override  
//   // ignore: library_private_types_in_public_api
//   _MyHomePageState createState() => _MyHomePageState();  
// }  
  
// class _MyHomePageState extends State<MyHomePage> {  
//   @override
//   void initState() {
//     super.initState();
//   }
//   @override
//   void dispose() {
//     super.dispose();
//   }
//   // ignore: prefer_typing_uninitialized_variables
//   var _imgPath;
  
//   /*相册*/
//   _openGallery() async {
//     final ImagePicker picker = ImagePicker();
//     var image = await picker.pickImage(source: ImageSource.gallery);
//     // var image = await ImagePicker.pickImage(source: ImageSource.gallery);
//     setState(() {
//       _imgPath = image;
//     });
    
//   }
  
//   Future<void> pickImage() async {  
//     final pickedFile = await ImagePicker().pickImage(source: ImageSource.gallery);  
//     if (pickedFile != null) {  
//       setState(() {  
//         _selectedImage = File(pickedFile.path);  
//       });  
//     } else {  
//       // ignore: avoid_print
//       print('No image selected.');  
//     }  
//   }  
  
//   @override  
//   Widget build(BuildContext context) {  
//     return Scaffold(  
//       appBar: AppBar(  
//         title: const Text('Flutter Image Picker Example'),  
//       ),  
//       body: Center(  
//         child: _imgPath != null  
//             ? Image.file(_imgPath)  
//             : const Text('Select an image from the gallery'),  
//       ),  
//       floatingActionButton: FloatingActionButton(  
//         onPressed: _openGallery,  
//         tooltip: 'Pick Image',  
//         child: const Icon(Icons.photo_library),  
//       ),  
//     );  
//   }  
// }

